import React, { createContext, useContext, useState, useEffect, ReactNode } from 'react';
import supabaseAuthService from '../services/authService'
import type { User as SupabaseUser, Session } from '@supabase/supabase-js';

interface UserProfile {
  id: string;
  email: string;
  name?: string;
  role: string;
  avatar_url?: string;
  created_at: string;
  updated_at: string;
}

interface User extends SupabaseUser {
  profile?: UserProfile;
}

interface AuthContextType {
  user: User | null;
  session: Session | null;
  profile: UserProfile | null;
  isAuthenticated: boolean;
  loading: boolean;
  signIn: (email: string, password: string) => Promise<any>;
  signUp: (email: string, password: string, name?: string) => Promise<any>;
  signOut: () => Promise<void>;
  refreshSession: () => Promise<void>;
}

interface AuthProviderProps {
  children: ReactNode;
}

const AuthContext = createContext<AuthContextType | undefined>(undefined);

export const useAuth = (): AuthContextType => {
  const context = useContext(AuthContext);
  if (!context) {
    throw new Error('useAuth must be used within an AuthProvider');
  }
  return context;
};

export const AuthProvider: React.FC<AuthProviderProps> = ({ children }) => {
  const [user, setUser] = useState<User | null>(null);
  const [session, setSession] = useState<Session | null>(null);
  const [profile, setProfile] = useState<UserProfile | null>(null);
  const [loading, setLoading] = useState<boolean>(true);
  const [isAuthenticated, setIsAuthenticated] = useState<boolean>(false);
  const [authService, setAuthService] = useState<any>(null);

  // 初始化认证服务
  useEffect(() => {
    const initAuthService = async () => {
      try {
        setAuthService(supabaseAuthService);
        await initializeAuth(supabaseAuthService);
      } catch (error) {
        console.error('初始化认证服务失败:', error);
        setLoading(false);
      }
    };

    initAuthService();
  }, []);

  // 监听认证状态变化（仅在 Supabase 模式下）
  useEffect(() => {
    if (!authService) {
      return;
    }

    const { data: { subscription } } = authService.onAuthStateChange(async (event: string, session: Session | null) => {
      console.log('Auth state changed:', event, session);

      if (event === 'SIGNED_IN' && session) {
        await handleAuthStateChange(session);
      } else if (event === 'SIGNED_OUT') {
        handleSignOut();
      } else if (event === 'TOKEN_REFRESHED' && session) {
        await handleAuthStateChange(session);
      }

      setLoading(false);
    });

    return () => {
      subscription.unsubscribe();
    };
  }, [authService]);

  const initializeAuth = async (service: any): Promise<void> => {
    try {
      setLoading(true);


      const currentSession = await service.getCurrentSession();

      if (currentSession) {
        await handleAuthStateChange(currentSession);
      } else {
        handleSignOut();
      }

    } catch (error) {
      console.error('初始化认证状态失败:', error);
      handleSignOut();
    } finally {
      setLoading(false);
    }
  };

  const handleAuthStateChange = async (session: Session): Promise<void> => {
    try {
      setSession(session);
      setUser(session.user as User);
      setIsAuthenticated(true);

      // 获取用户配置文件
      // 这里可以添加获取用户配置文件的逻辑
      // const userProfile = await getUserProfile(session.user.id);
      // setProfile(userProfile);
    } catch (error) {
      console.error('处理认证状态变化失败:', error);
    }
  };

  const handleSignOut = (): void => {
    setUser(null);
    setSession(null);
    setProfile(null);
    setIsAuthenticated(false);
  };

  const signIn = async (email: string, password: string): Promise<any> => {
    if (!authService) {
      throw new Error('认证服务未初始化');
    }

    try {
      setLoading(true);
      const response = await authService.signIn(email, password);

      if (response.success) {
        if (response.data) {
          setUser(response.data.user as User);
          setSession(response.data.session);
          setProfile(response.data.profile || null);
        }
        setIsAuthenticated(true);
      }

      return response;
    } catch (error) {
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const signUp = async (email: string, password: string, name?: string): Promise<any> => {
    if (!authService) {
      throw new Error('认证服务未初始化');
    }

    try {
      setLoading(true);
      let response;
      response = await authService.signUp(email, password, { name });
      if (response.success) {
        if (response.data) {
          setUser(response.data.user as User);
          setSession(response.data.session);
          setProfile(response.data.profile || null);
        }
        setIsAuthenticated(true);
      }
      return response;
    } catch (error) {
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const signOut = async (): Promise<void> => {
    if (!authService) {
      return;
    }

    try {
      setLoading(true);
      await authService.signOut();
      handleSignOut();
    } catch (error) {
      console.error('登出失败:', error);
      // 即使登出失败，也要清除本地状态
      handleSignOut();
    } finally {
      setLoading(false);
    }
  };


  const refreshSession = async (): Promise<void> => {
    if (!authService) {
      return;
    }

    try {
      const { session: newSession, user: newUser } = await authService.refreshSession();

      if (newSession && newUser) {
        setSession(newSession);
        setUser(newUser as User);
        setIsAuthenticated(true);
      } else {
        handleSignOut();
      }
    } catch (error) {
      console.error('刷新会话失败:', error);
      handleSignOut();
    }
  };

  const value: AuthContextType = {
    user,
    session,
    profile,
    isAuthenticated,
    loading,
    signIn,
    signUp,
    signOut,
    refreshSession
  };

  return (
    <AuthContext.Provider value={value}>
      {children}
    </AuthContext.Provider>
  );
};